<template>
  <div class="like-container">
    <div class="like-header">
      <h2>收到的点赞</h2>
      <div v-if="profile.unreadLikeCount > 0" class="unread-badge">
        {{ profile.unreadLikeCount }} 条未读
      </div>
    </div>
    
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>
    
    <div v-else-if="likes.length === 0" class="empty-state">
      <t-icon name="heart" class="empty-icon" />
      <p>暂无收到的点赞</p>
    </div>
    
    <div v-else class="like-list">
      <div v-for="(like, index) in likes" :key="index" class="like-item" :class="{ 'unread': !like.userLike.isRead }">
        <div class="like-user-info">
          <div class="user-avatar" @click="navigateToUserProfile(like.userLike.userId)">
            <img :src="userAvatars[like.userLike.userId] || defaultAvatarImg" alt="用户头像" />
          </div>
          <div class="like-details">
            <div class="like-user-action">
              <span class="username" @click="navigateToUserProfile(like.userLike.userId)">{{ usernames[like.userLike.userId] || '加载中...' }}</span>
              <span class="action-text">赞了你的{{ getContentTypeText(like.contentType) }}</span>
              <span v-if="!like.userLike.isRead" class="unread-dot" title="未读消息"></span>
            </div>
            <div class="like-time">{{ formatTime(like.userLike.likedAt) }}</div>
          </div>
          <div v-if="!like.userLike.isRead" class="mark-read-btn">
            <el-button 
              type="primary" 
              size="small" 
              :loading="like.markingAsRead" 
              @click.stop="markAsRead(like)"
            >
              标为已读
            </el-button>
          </div>
        </div>
        
        <div class="like-content" @click="navigateToContent(like)">
          <div class="content-preview">
            <template v-if="like.contentType === 'article'">
              <h3 class="content-title">{{ like.content.title }}</h3>
              <p class="content-description">{{ like.content.description }}</p>
            </template>
            
            <template v-else-if="like.contentType === 'question'">
              <h3 class="content-title">{{ like.content.title }}</h3>
              <p class="content-description" v-html="truncateText(like.content.content, 100)"></p>
            </template>
            <template v-else-if="like.contentType === 'answer'">
              <h3 class="content-title">回答了：{{ like.question.title }}</h3>
              <p class="content-description">{{ truncateText(like.content.content, 100) }}</p>
            </template>
            
            <template v-else-if="like.contentType === 'comment'">
              <p class="content-description">{{ like.content.content }}</p>
            </template>
          </div>
          
          <div class="content-stats">
            <span class="stat-item">
              <t-icon name="heart" /> {{ like.content.likeCount || 0 }}
            </span>
            <span v-if="like.contentType !== 'comment'" class="stat-item">
              <t-icon name="bookmark" /> {{ like.content.favoriteCount || 0 }}
            </span>
            <span class="stat-item">
              <t-icon name="chat" /> {{ like.content.commentCount || 0 }}
            </span>
          </div>
        </div>
      </div>
      
      <div v-if="hasMore" class="load-more">
        <el-button :loading="loadingMore" @click="loadMoreLikes">加载更多</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElSkeleton } from 'element-plus';
import { useUserStore } from '@/stores/userStore';
import { storeToRefs } from 'pinia';
import { getReceiveLikes, findUserById, markLikeAsRead } from '@/api/userApi';
import defaultAvatarImg from '@/imgs/avatar.png';

const router = useRouter();
const userStore = useUserStore();
const { profile } = storeToRefs(userStore);

// 数据状态
const likes = ref([]);
const loading = ref(true);
const loadingMore = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const hasMore = ref(true);
const usernames = ref({});
const userAvatars = ref({});

// 获取点赞列表
const fetchLikes = async (reset = false) => {
  if (reset) {
    currentPage.value = 1;
    likes.value = [];
    loading.value = true;
  } else {
    loadingMore.value = true;
  }
  
  try {
    const response = await getReceiveLikes(profile.value.id, currentPage.value, pageSize.value);
    const newLikes = response.data;
    
    if (newLikes.length < pageSize.value) {
      hasMore.value = false;
    }
    
    // 为每个点赞添加标记已读的加载状态
    newLikes.forEach(like => {
      like.markingAsRead = false;
    });
    
    likes.value = reset ? newLikes : [...likes.value, ...newLikes];
    
    // 获取用户信息
    await fetchUserInfo(newLikes);
    
  } catch (error) {
    console.error('获取点赞列表失败:', error);
    ElMessage.error('获取点赞列表失败');
  } finally {
    loading.value = false;
    loadingMore.value = false;
  }
};

// 标记为已读
const markAsRead = async (like) => {
  // 防止重复点击
  if (like.markingAsRead) return;
  
  // 设置加载状态
  like.markingAsRead = true;
  
  try {
    await markLikeAsRead({
      userId: profile.value.id,
      targetUserId: like.userLike.userId,
      contentId: like.userLike.contentId,
      contentType: like.contentType
    });
    
    // 更新状态
    like.userLike.isRead = true;
    
    // 更新未读消息计数
    if (profile.value.unreadLikeCount > 0) {
      profile.value.unreadLikeCount--;
    }
    
    ElMessage.success('已标记为已读');
  } catch (error) {
    console.error('标记已读失败:', error);
    ElMessage.error('标记已读失败');
  } finally {
    like.markingAsRead = false;
  }
};

// 获取用户信息
const fetchUserInfo = async (likesList) => {
  const userIds = likesList
    .map(like => like.userLike.userId)
    .filter(id => !usernames.value[id]);
  
  // 去重
  const uniqueUserIds = [...new Set(userIds)];
  
  const promises = uniqueUserIds.map(async (userId) => {
    try {
      const response = await findUserById(userId);
      const user = response.data;
      usernames.value[userId] = user.username;
      userAvatars.value[userId] = user.profilePicture || defaultAvatarImg;
    } catch (error) {
      console.error(`获取用户 ${userId} 信息失败:`, error);
      usernames.value[userId] = '未知用户';
    }
  });
  
  await Promise.all(promises);
};

// 加载更多
const loadMoreLikes = async () => {
  if (loadingMore.value) return;
  currentPage.value++;
  await fetchLikes();
};

// 格式化时间
const formatTime = (timeStr) => {
  const date = new Date(timeStr);
  const now = new Date();
  const diff = now - date;
  
  // 小于1分钟
  if (diff < 60 * 1000) {
    return '刚刚';
  }
  
  // 小于1小时
  if (diff < 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 1000))}分钟前`;
  }
  
  // 小于24小时
  if (diff < 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 60 * 1000))}小时前`;
  }
  
  // 小于30天
  if (diff < 30 * 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`;
  }
  
  // 大于30天，显示具体日期
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 截断文本
const truncateText = (text, maxLength) => {
  if (!text) return '';
  return text.length > maxLength ? text.substring(0, maxLength) + '...' : text;
};

// 获取内容类型文本
const getContentTypeText = (type) => {
  switch (type) {
    case 'article':
      return '文章';
    case 'question':
      return '问题';
    case 'answer':
      return '回答';
    case 'comment':
      return '评论';
    default:
      return '内容';
  }
};

// 导航到用户主页
const navigateToUserProfile = (userId) => {
  router.push(`/home/userCenter/${userId}`);
};

// 导航到内容页面
const navigateToContent = (like) => {
  // 如果消息未读且不是评论类型，则在跳转前标记为已读
  if (!like.userLike.isRead && like.contentType !== 'comment') {
    markAsRead(like);
  }
  
  switch (like.contentType) {
    case 'article':
      router.push(`/home/article/${like.content.id}`);
      break;
    case 'question':
      router.push(`/home/question/${like.content.id}`);
      break;
    case 'answer':
      router.push(`/home/question/${like.question.id}`);
      break;
    case 'comment':
      // 评论可能在不同类型的内容下，这里简化处理
      ElMessage.info('暂不支持直接跳转到评论位置');
      break;
  }
};

onMounted(async () => {
  await fetchLikes(true);
});
</script>

<style scoped>
.like-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.like-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.like-header h2 {
  margin: 0;
  font-size: 1.8rem;
  color: #303133;
}

.unread-badge {
  margin-left: 10px;
  background-color: #f56c6c;
  color: white;
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 0.8rem;
}

.loading-container {
  padding: 20px 0;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
  color: #909399;
}

.empty-icon {
  font-size: 3rem;
  margin-bottom: 15px;
  color: #dcdfe6;
}

.like-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.like-item {
  display: flex;
  flex-direction: column;
  padding: 15px;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.like-item:hover {
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.like-item.unread {
  border-left: 3px solid #f56c6c;
  background-color: #fff9f9;
}

.like-user-info {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 10px;
  cursor: pointer;
}

.user-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.like-details {
  flex: 1;
}

.like-user-action {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 0.95rem;
}

.username {
  font-weight: 600;
  color: #303133;
  cursor: pointer;
}

.username:hover {
  color: #409eff;
}

.action-text {
  color: #606266;
}

.unread-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #f56c6c;
  display: inline-block;
  margin-left: 5px;
}

.mark-read-btn {
  margin-left: 10px;
}

.like-time {
  font-size: 0.8rem;
  color: #909399;
  margin-top: 3px;
}

.like-content {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 6px;
  cursor: pointer;
}

.like-content:hover {
  background-color: #ebeef5;
}

.content-title {
  margin: 0 0 8px 0;
  font-size: 1.1rem;
  color: #303133;
}

.content-description {
  margin: 0;
  font-size: 0.9rem;
  color: #606266;
  line-height: 1.5;
}

.content-stats {
  display: flex;
  gap: 15px;
  margin-top: 10px;
  font-size: 0.85rem;
  color: #909399;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 3px;
}

.load-more {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
